package framework.rpc.protocol.register;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import framework.rpc.util.IoUtil;
import org.springframework.util.CollectionUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

/**
 * 远程注册中心 ===》 Zookeeper等
 * 这里需要使用Redis缓存才能实现消费者与服务提供者都拿到相同的数据
 *
 * @author ldanniel
 */
public class RemoteMapRegister {
    private static final Map<String, List<RegisterUrl>> REGISTER = new HashMap<>();

    public static void registry(String interfaceName, RegisterUrl url) {
        List<RegisterUrl> urlList = REGISTER.get(interfaceName);
        if (CollectionUtils.isEmpty(urlList)) {
            urlList = new ArrayList<>();
        }
        urlList.add(url);
        REGISTER.put(interfaceName, urlList);
        IoUtil.save(REGISTER);
    }

    public static List<RegisterUrl> getRegistryList(String interfaceName) {
        Map listMap = null;
        try {
            InputStream inputStream = new FileInputStream("D:\\Workspace\\java-design-mode\\framework-rpc\\registry_center.properties");
            listMap = JSONObject.parseObject(IoUtil.read(inputStream), Map.class);
            List<RegisterUrl> list = (List<RegisterUrl>) listMap.get(interfaceName);
            List<RegisterUrl> registerUrlList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                registerUrlList.add(JSONObject.parseObject(JSONObject.toJSONString(list.get(i)), RegisterUrl.class));
            }
            return registerUrlList;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
